<?php
class Agitum_Model_Page extends Agitum_Model_Tree implements Zend_Acl_Resource_Interface
{
	protected $_t_class = 'Agitum_Model_DbTable_Page';
	
	protected function init() 
	{
		parent::init();
		$this->_fields['title'] = array_merge($this->_fields['title'], array('label' => 'Заголовок', 'readOnly' => false));
		$this->_fields['name'] = array_merge($this->_fields['name'], array('label' => 'Маршрут', 'readOnly' => false));
		$this->_fields['visible'] = array_merge($this->_fields['visible'], array('label' => 'Видимо в меню', 'readOnly' => false));
	}
		
	public function getResourceId()
	{
		return $this->id;
	}
	
	public function getContainer() 
	{
	    $db = Zend_Registry::get('Zend_Db');
		$select = $db->select();
		$select->from( array('p' => 'page') )
			->joinLeft( array('r'=>'route'), 'r.name = p.name', array('controller', 'action', 'module') )
			->order(array('p.trail'))
			;
		$rows = $select->query()->fetchAll();

		$pages = array();
		$parents = array();
        foreach ( $rows as $id => $row )
        {
            $item = array(
        	 	'id'         => $row['id'],
        		'module'     => $row['module'],
        		'controller' => $row['controller'],
        	 	'action'     => $row['action'],
        	 	'route'		 => $row['name'],
        	 	'resource'   => $row['name'],
        	 	'privilege'  => $row['action'],
        		'label'      => $row['title'],
        	 	'visible'    => $row['visible'],
        	 	'level'      => $row['level'],
                'order'		 => $row['sorder']
        	);
        	$item['pages'] = array();
        	$parents[ $row['id'] ] = &$item['pages'];
        	if ( !isset($parents[ $row['pid'] ]) ) {
        		$pages[] = $item;
        	} else {
        		$parents[ $row['pid'] ][] = $item;
        	}
        }
        unset($parents);
        return $pages;
	}
	
	public static function findByMVC($mvc = array())
	{
	    $db = Zend_Registry::get('Zend_Db');
	    $select = $db->select();
	    $select->from(array('p'=>'page'))
		        ->joinCross(array('r'=>'route'), array())
		        ->where('r.module = ?', $mvc['module'])
		        ->where('r.action = ?', $mvc['action'])
		        ->where('r.controller = ?', $mvc['controller'])
		        ->where('p.name = r.name');
        $row = $select->query()->fetch();
        if ( $row ) {
            return new Agitum_Model_Page($row);
        }
        return new Agitum_Model_Page();
	}
}